package top.tagao.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.tagao.yygh.enums.PaymentTypeEnum;
import top.tagao.yygh.enums.RefundStatusEnum;
import top.tagao.yygh.model.order.OrderInfo;
import top.tagao.yygh.model.order.PaymentInfo;
import top.tagao.yygh.model.order.RefundInfo;
import top.tagao.yygh.order.service.OrderService;
import top.tagao.yygh.order.service.PaymentService;
import top.tagao.yygh.order.service.RefundInfoService;
import top.tagao.yygh.order.service.WeixinService;
import top.tagao.yygh.order.utils.ConstantPropertiesUtils;
import top.tagao.yygh.order.utils.HttpClient;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author fu-xiao-liu
 * @Date 2022/3/15 16:02
 */
@Service
public class WeixinServiceImpl implements WeixinService {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RefundInfoService refundInfoService;


    /**
     * @date  生成下单二维码
     * @param orderId
     * @return java.util.Map
     */
    @Override
    @Transactional
    public Map createNative(Long orderId) {

        try {

            // 0. 先判断Redis是否存在了订单号的支付信息
            Map payMap = (Map)redisTemplate.opsForValue().get(orderId.toString());
            if ( null != payMap){
                return payMap;
            }

            // 1. 根据OrderId获取订单号的信息
            OrderInfo orderInfo = orderService.getById(orderId);
            // 2. 向支付记录表添加信息
            paymentService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());
            // 3. 设置发送请求二维码的参数
            Map paramMap = new HashMap();
            //公众账号ID	appid
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            //商户号	mch_id
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            //随机字符串	nonce_str
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            //签名	sign
            //商品描述	body
            paramMap.put("body", orderInfo.getReserveDate() + "就诊"+ orderInfo.getDepname());
            //商户订单号	out_trade_no
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
            //标价金额(单位为分)	total_fee
            //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "2"); //为了测试，统一写成这个值
            //终端IP	spbill_create_ip
            paramMap.put("spbill_create_ip", "127.0.0.1");
            //通知地址	notify_url
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
            //交易类型	trade_type
            paramMap.put("trade_type", "NATIVE");

            // 4. 调用微信生成二维码接口,httpclient调用
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");

            // 5. 将参数转换xml格式，使用商户key进行加密
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();

            // 6. 返回相关数据转为Map
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            // 7. 封装返回结果集
            payMap = new HashMap<>();
            payMap.put("orderId",orderId);
            payMap.put("totalFee", orderInfo.getAmount());
            payMap.put("resultCode", resultMap.get("result_code"));
            payMap.put("codeUrl", resultMap.get("code_url")); //二维码地址
            if(resultMap.get("result_code") != null) {
                redisTemplate.opsForValue().set(orderId.toString(),paramMap,120, TimeUnit.MINUTES);
            }
            return payMap;
        }catch (Exception e) {
            e.printStackTrace();
            return null;

        }

    }

    /**
     * @date  查询支付状态
     * @param orderId
     */
    @Override
    public Map<String, String> queryPayStatus(Long orderId) {
        try {
            // 1. 根据orderId获取订单信息
            OrderInfo orderInfo = orderService.getById(orderId);

            // 2. 封装请求参数
            HashMap<String, String> paramMap = new HashMap<>();
            paramMap.put("appid",ConstantPropertiesUtils.APPID);
            paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);
            paramMap.put("out_trade_no",orderInfo.getOutTradeNo());
            paramMap.put("nonce_str",WXPayUtil.generateNonceStr());

            // 3. 调用微信查询订单接口,httpclient调用
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();

            // 4. 得到微信接口返回数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            System.out.println("支付状态resultMap:"+resultMap);

            return resultMap;
        }catch (Exception e){
            e.printStackTrace();
            return  null;
        }

    }

    /**
     * @date  退款
     * @param orderId
     * @return java.lang.Boolean
     */
    @Override
    public Boolean refund(Long orderId) {
        try {
            // 1. 通过订单编号获取支付详情信息
            PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderId, PaymentTypeEnum.WEIXIN.getStatus());

            // 2. 生成退款信息
            RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);
            // 3. 判断是否已经退款
            if (refundInfo.getRefundStatus() == RefundStatusEnum.REFUND.getStatus()){
                return true;
            }
            // 4. 设置请求参数
            Map<String,String> paramMap = new HashMap<>();
            //公众账号ID	appid
            paramMap.put("appid",ConstantPropertiesUtils.APPID);
            //商户号	mch_id
            paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);
            //随机字符串	nonce_str
            paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
            //签名	sign
            //商户订单号	out_trade_no
            paramMap.put("out_trade_no",paymentInfo.getOutTradeNo());
            //微信支付订单号	transaction_id
            paramMap.put("transaction_id",paymentInfo.getTradeNo());
            //商户退款单号	out_refund_no
            paramMap.put("out_refund_no","tk"+paymentInfo.getOutTradeNo());
            //订单金额	total_fee
            paramMap.put("total_fee","2");
            //退款金额	refund_fee
            paramMap.put("refund_fee","2");

            String paramXml = WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY);

            // 5. 调用微信查询订单接口,httpclient调用
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(paramXml);
            client.setHttps(true);

            // 6. 设置证书信息
            client.setCert(true);
            client.setCertPassword(ConstantPropertiesUtils.PARTNER);
            client.post();

            // 7. 接收返回数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            if (null != resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code") )){
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
                return true;
            }

            return  false;
        }catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


}
